//
//  QLMCarTypeView.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2017/10/13.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMCarTypeView.h"
#import "QLMPeijianListCVCell.h"
#import "QLMCartypeCReView.h"

@interface QLMCarTypeView()<UICollectionViewDelegate,UICollectionViewDataSource>{
    QLMCartypeCReView *reusableview;
    UILabel *label;
    
    NSString *carTypeStr;
    NSString *carSeriStr;
    QLMPeijianListCVCell *pjCollectionCell;
    NSString *keyStr;
    
    UIView *lineView;
    UILabel *rTipLabel;
}

@property (nonatomic,strong) UICollectionView *pjCollectionView;
@property (nonatomic,strong) NSString *titleName;
@property (nonatomic,strong) NSString *titleType;
@property (nonatomic,assign) BOOL isdidTapRow;

@property (nonatomic,strong) NSArray *firstLetterArray;
@property (nonatomic,strong) NSDictionary *itemDic;

@end

@implementation QLMCarTypeView

- (id) init{
    self=[super init];
    if (self){
        _titleName=@"三一重工";
        _titleType=@"斗山";
        
        _itemDic=[NSDictionary dictionary];
        _addItemArray=[NSMutableArray array];
        _firstLetterArray=[NSMutableArray array];
        [self aCreatMainView];
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (void)tap123{
    
    carTypeStr=nil;
    carSeriStr=nil;
    
    [self removeFromSuperview];
}

- (void)requestBrandSerData:(NSString *)brandId{
    
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:_machineTypeId forKey:@"machineTypeId"];
    [paramerDic setObject:brandId forKey:@"brandId"];
    
    [ClientTool postUrlPath:@"/test/equipment/modelList" withParamers:paramerDic andBody:nil
                    success:^(id responseObject){
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            rTipLabel.hidden=YES;

                            if ([responseObject[@"modelList"] count]==0) {
                                
                                rTipLabel.text=nil;
                                
                                [_addItemArray removeAllObjects];
                                [_pjCollectionView reloadData];
                                return;
                            }
                            
//                            keyStr=[[responseObject[@"modelList"] allKeys] objectAtIndex:0];
                            _addItemArray=responseObject[@"modelList"]; //[responseObject[@"modelList"] objectForKey:keyStr];
//                            [self _creatAFirstLetterArray:[NSArray arrayWithObjects:keyStr,nil]];
                            
                            
                            [_pjCollectionView reloadData];
                            
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)aCreatMainView{
    
    UIView *coverView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    coverView.backgroundColor = [UIColor blackColor];
    coverView.alpha = 0.7;
    coverView.userInteractionEnabled=YES;
    [self addSubview:coverView];
    
    UITapGestureRecognizer *tap123=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap123)];
    [coverView addGestureRecognizer:tap123];
    
    UIView *alertView = [[UIView alloc] init];
    alertView.frame = CGRectMake(60,0,kScreen_width-80,kScreen_height);
    alertView.backgroundColor = [UIColor whiteColor];
    alertView.userInteractionEnabled=YES;
    [self addSubview:alertView];
    
    label = [[UILabel alloc] initWithFrame:CGRectMake(5, 27, alertView.bounds.size.width-5*2, 30)];
    label.text = @"品牌";
    label.backgroundColor=[UIColor clearColor];
    label.font = [UIFont systemFontOfSize:15];
    label.textAlignment = NSTextAlignmentCenter;
    [alertView addSubview:label];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    layout.minimumInteritemSpacing = 0;// 垂直方向的间距
    layout.minimumLineSpacing = 0; // 水平方向的间距
    
    _pjCollectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 60, alertView.bounds.size.width, kScreen_height-60) collectionViewLayout:layout];
    _pjCollectionView.delegate=self;
    _pjCollectionView.dataSource=self;
    _pjCollectionView.showsVerticalScrollIndicator=NO;
    _pjCollectionView.backgroundColor=[UIColor whiteColor];
    _pjCollectionView.alwaysBounceVertical = YES;
    _pjCollectionView.collectionViewLayout=layout;
    [_pjCollectionView registerClass:[QLMPeijianListCVCell class] forCellWithReuseIdentifier:@"QLMPeijianListCVCellId"];
    [alertView addSubview:_pjCollectionView];
    
    [_pjCollectionView registerClass:[QLMCartypeCReView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionReusableViewId12"];
    
    lineView=[[UIView alloc] initWithFrame:CGRectMake(kScreen_width-20,0,20,kScreen_height)];
    lineView.backgroundColor=[UIColor whiteColor];
    lineView.userInteractionEnabled=YES;
    [self addSubview:lineView];
    
    rTipLabel=[[UILabel alloc] init];
    [rTipLabel setFrame:CGRectMake(0, 0, lineView.frame.size.width, lineView.frame.size.height)];
    rTipLabel.backgroundColor=[UIColor clearColor];
    rTipLabel.numberOfLines=0;
    rTipLabel.userInteractionEnabled=YES;
    rTipLabel.textColor=[UIColor blackColor];
    rTipLabel.font=[UIFont systemFontOfSize:13.0f];
    [lineView addSubview:rTipLabel];
    
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] init];
    [tap addTarget:self action:@selector(clickStarIndexView:)];
    [rTipLabel addGestureRecognizer:tap];
}

- (void)_creatAFirstLetterArray:(NSArray *)firstLetterArray{
    
    rTipLabel.frame=CGRectMake(0, kScreen_height/2-10 * firstLetterArray.count, 20,20 * firstLetterArray.count);
    
    NSString *indexesString = [firstLetterArray componentsJoinedByString:@"\n"];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.minimumLineHeight = 20;
    paragraphStyle.alignment = NSTextAlignmentCenter;
    NSAttributedString *attriString = [[NSAttributedString alloc] initWithString:indexesString   attributes:@{ NSParagraphStyleAttributeName : paragraphStyle, NSForegroundColorAttributeName:UIColorFromRGB(0x999999),NSBaselineOffsetAttributeName:@(1)}];
    rTipLabel.attributedText = attriString;
}

-(void)clickStarIndexView:(UITapGestureRecognizer*)tap{
    
    CGPoint location = [tap locationInView:rTipLabel];
    NSInteger index = location.y / 20 ;
    
   CGRect destinationRect = [_pjCollectionView layoutAttributesForSupplementaryElementOfKind:UICollectionElementKindSectionHeader atIndexPath:[NSIndexPath indexPathForRow:0 inSection:index]].frame;
    
    CGFloat offsetY = MIN(destinationRect.origin.y,_pjCollectionView.contentSize.height-_pjCollectionView.frame.size.height);
    [_pjCollectionView setContentOffset:CGPointMake(0, offsetY) animated:NO];
}


#pragma mark - UICollectionView datasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (_isdidTapRow){
        return _addItemArray.count;
    }
    NSArray *tmpArray=_itemArray[section];
    return tmpArray.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (_isdidTapRow){
        return 1;
    }
    
    _firstLetterArray = [[_brandDic allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    [self _creatAFirstLetterArray:_firstLetterArray];
    return _firstLetterArray.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((kScreen_width-80-20)/3, 34);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifiew=@"QLMPeijianListCVCellId";
    pjCollectionCell=[collectionView dequeueReusableCellWithReuseIdentifier:identifiew forIndexPath:indexPath];
    
    if (_isdidTapRow){
        pjCollectionCell.pjnameLabel.text=[_addItemArray[indexPath.row] objectForKey:@"modelName"];
    }else{
        pjCollectionCell.pjnameLabel.text=[[_itemArray[indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"codeName"];
    }
    
    return pjCollectionCell;
}

/** section的margin*/
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 5, 5, 5);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout*)collectionViewLayout
minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout*)collectionViewLayout
minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    if([kind isEqualToString:UICollectionElementKindSectionHeader]){
    
        reusableview= [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionReusableViewId12" forIndexPath:indexPath];
        if (_isdidTapRow) {
            reusableview.tiplabel.text = keyStr;
        }else{
            reusableview.tiplabel.text = _firstLetterArray[indexPath.section];
        }
        return reusableview;
      
    }else if([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(kScreen_width-80, 34);
}

#pragma mark -- UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    if (_isdidTapRow) {
        _isdidTapRow=NO;
        carSeriStr=[NSString stringWithFormat:@"%@%@",[_addItemArray[indexPath.row] objectForKey:@"modelName"],_itemDic[@"productName"]];
        
        [self removeFromSuperview];
    }else{
        _isdidTapRow=YES;
        label.text = @"系列";
        
        NSString *brandIdStr=[[_itemArray[indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"brandId"];
        
        _itemDic=[_itemArray[indexPath.section] objectAtIndex:indexPath.row];
        
        [self requestBrandSerData:brandIdStr];
        carTypeStr=[[_itemArray[indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"codeName"];
    }
    
    if ([carTypeStr length]!=0&&[carSeriStr length]!=0) {
        self.cartypeBlock(carTypeStr,carSeriStr,_itemDic,_addItemArray[indexPath.row]);
    }
}

@end
